//package main server
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"runtime"

	"gitee.com/wang_cyi/TryEverything/promise"
	"gitee.com/wang_cyi/TryEverything/public"
	"gitee.com/wang_cyi/TryEverything/server"
)

func init() {
	var path string
	if runtime.GOOS == "windows" {
		path = "server_conf.json"
	} else {
		path = "srcipts/server_conf_ubuntu.json"
	}
	f, err := os.Open(path)
	if err != nil {
		log.Fatalf("[ERROR] Fail to open config file: %s", err)
	}

	if err = json.NewDecoder(f).Decode(&Cfg); err != nil {
		log.Fatalf("[ERROR] Fail to decode config file: %s", err)
	}

	outfile, err := os.OpenFile("./promise.log", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) //打开文件，若果文件不存在就创建一个同名文件并打开
	if err != nil {
		fmt.Println(*outfile, "open failed")
		os.Exit(1)
	}

	log.SetOutput(outfile) //设置log的输出文件，不设置log输出默认为stdout
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}

var (
	//Cfg is
	Cfg public.Config
)

//Supervisor 管理类
type Supervisor struct {
	Data        *public.Config
	messagesQue chan string
	RtmpMap     map[string]string //Golang的引用类型包括 slice、map 和 channel
	LifeMap     map[string]*promise.LifeData
}

func (p *Supervisor) create() {
	p.messagesQue = make(chan string)
	p.RtmpMap = make(map[string]string)
	p.LifeMap = make(map[string]*promise.LifeData)
	eat := new(promise.LifeData)
	p.LifeMap["eat"] = eat

	book := new(promise.LifeData)
	p.LifeMap["book"] = book

	run := new(promise.LifeData)
	p.LifeMap["run"] = run

	sleep := new(promise.LifeData)
	p.LifeMap["sleep"] = sleep

	money := new(promise.LifeData)
	p.LifeMap["money"] = money

}

//PromiseDailyTask PromiseDailyTask
func (p *Supervisor) PromiseDailyTask() {
	//定时提醒任务
	go promise.RtmpShareTask(p.RtmpMap)

	go promise.DailyPlan(p.messagesQue, Cfg)

}

//ReadWriteTaskChan 需要消息驱动
func (p *Supervisor) ReadWriteTaskChan() {

	//send
	//go promise.TaskWriteDeal(p.messagesQue)
	//read
	go func() {
		for {
			select {
			case data := <-p.messagesQue:
				//数据可以读
				//fmt.Println("read", data)
				log.Println("read", data)
				promise.TaskReadDeal(data)

			}
		}
	}()

}

//StartTryEveryRun 一天任务
func (p *Supervisor) StartTryEveryRun() {

	//1 消息驱动任务
	go p.ReadWriteTaskChan()

	//2 定时任务：一天执行一次
	go p.PromiseDailyTask()   //实施任务 马上处理
	go public.CronDaily(&Cfg) //定时任务迁移到上面去

	//3 周期性任务 重复执行
	task := promise.NewTask(promise.YouCanDoIt)

	scheduling := promise.NewScheduling(task)

	//执行任务
	scheduling.CronTab()

	channel := make(chan int)
	//防止主进程优先退出
	for {
		fmt.Println("Wait forever ")
		<-channel
	}
}

func hello(w http.ResponseWriter, req *http.Request) {

	fmt.Fprintf(w, "hello\n")
}

//main 类似产品 https://github.com/shylinux
func main() {

	supervisor := &Supervisor{Data: &Cfg}
	supervisor.create()
	go supervisor.StartTryEveryRun() //开启每天任务

	//构建http服务
	mux := http.NewServeMux()
	mux.Handle("/", &indexHandler{})
	mux.Handle("/rtmp", &RtmpHandler{RtmpMap: supervisor.RtmpMap})
	mux.Handle("/note", &ReadBookHandler{supervisor.messagesQue})
	mux.Handle("/life", &LifeHandler{supervisor.LifeMap, Cfg})
	mux.Handle("/wechat", &server.WeCHatHandler{LifeMap: supervisor.LifeMap})

	fmt.Println("TryEverthing start ")
	ip := "localhost:8090"
	if runtime.GOOS == "linux" {
		ip = "74.120.174.137:8090"

	}
	log.Println(ip, "start")
	err := http.ListenAndServe(ip, mux)
	if err != nil {
		log.Println(err)
	}

}
